package com.woniu.aimd.config.ai.tools;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
public class WeathetTool {

    @Value("${weather.api.key:rPYhdzOIPBhENy48Ps2Z1zX3Cc}")
    private String apiKey;

    @Value("${weather.api.url:https://api.shwgij.com/api/tianqi/tianqi}")
    private String apiUrl;
//
    private final ObjectMapper objectMapper;

    public WeathetTool(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 通过外部API获取指定城市和日期的天气信息
     * @param city 城市名称
     * @param date 日期，格式：yyyy-MM-dd
     * @return 天气信息字符串
     */
    @Tool(description = "查天气")
    public String selectWeather(@ToolParam(description = "地区",required = true
    )
                                       String province,String city, String date) {
        try {
            // 验证城市和日期
            if (city == null || city.isEmpty()) {
                return "请提供有效的城市名称";
            }
            System.out.println("查询城市："+city);
            // 构建URL
            StringBuilder urlBuilder = new StringBuilder(apiUrl);
            urlBuilder.append("?key=").append(apiKey);
            urlBuilder.append("&m=2");  // 强制添加m参数，取值1或2
            urlBuilder.append("&province=").append(URLEncoder.encode(province, StandardCharsets.UTF_8));
            urlBuilder.append("&city=").append(URLEncoder.encode(city, StandardCharsets.UTF_8.toString()));

            System.out.println("当前查询城市所属省份"+province);
            // 如果提供了日期，则添加日期参数
            if (date != null && !date.isEmpty()) {
                urlBuilder.append("&date=").append(date);
            }
            System.out.println("查询日期："+date);
            // 创建URL对象并打开连接
            URL url = new URL(urlBuilder.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("正从外部api查询天气");
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
//                    System.out.println("拿到的信息列表：");
//                    System.out.println(line);
//                    System.out.println(response);
                }
                reader.close();

                // 解析JSON响应
                return parseWeatherResponse(response.toString());
            } else {
                return "API请求失败，响应码: " + responseCode;
            }
        } catch (Exception e) {
            return "获取天气信息失败: " + e.getMessage();
        }
    }

    /**
     * 解析API返回的JSON响应
     */
    private String parseWeatherResponse(String jsonResponse) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResponse);

            // 检查API是否返回成功
            if (rootNode.has("code") && rootNode.get("code").asInt() == 201) {
                // 假设API返回的天气数据在data节点下
                if (rootNode.has("data")&& rootNode.get("data")
                                .has("observe")) {
                    JsonNode observeNode  = rootNode.get("data").get("observe");
                    StringBuilder weatherInfo = new StringBuilder();

                    // 提取天气信息，这里需要根据实际API返回格式调整
                    if (observeNode.has("city")) {
                        weatherInfo.append("城市: ").append(observeNode.get("city").asText()).append("\n");
                    }
                    if (observeNode.has("date")) {
                        weatherInfo.append("日期: ").append(observeNode.get("date").asText()).append("\n");

                    }
                    if (observeNode.has("weather")) {
                        weatherInfo.append("天气: ").append(observeNode.get("weather").asText()).append("\n");
                    }
                    if (observeNode.has("temperature")) {
                        weatherInfo.append("温度: ").append(observeNode.get("temperature").asText()).append("°C\n");
                    }
                    if (observeNode.has("wind")) {
                        weatherInfo.append("风力: ").append(observeNode.get("wind").asText()).append("\n");
                    }
                    if (observeNode.has("humidity")) {
                        weatherInfo.append("湿度: ").append(observeNode.get("humidity").asText()).append("%\n");
                    }

                    // 提取空气质量信息
                    if (rootNode.get("data").has("air")) {
                        JsonNode airNode = rootNode.get("data").get("air");
                        weatherInfo.append("空气质量: ").append(airNode.get("aqi_name").asText())
                                .append(" (AQI: ").append(airNode.get("aqi").asText()).append(")\n");
                    }

                    // 提取高温预警信息
                    if (rootNode.get("data").has("alarm") && rootNode.get("data").get("alarm").isArray()) {
                        JsonNode alarmNode = rootNode.get("data").get("alarm").get(0);
                        if (alarmNode != null && alarmNode.has("detail")) {
                            weatherInfo.append("预警信息: ").append(alarmNode.get("detail").asText()).append("\n");
                        }
                    }

                    return weatherInfo.toString();
                }
            }

            // 如果API返回错误或格式不符合预期
            if (rootNode.has("msg")) {
                return "API错误: " + rootNode.get("msg").asText();
            }

            return "无法解析天气信息: " + jsonResponse;
        } catch (Exception e) {
            return "解析天气信息失败: " + e.getMessage();
        }
    }

    /**
     * 检查日期是否有效（未来7天内）
     */
    public boolean isValidDate(String date) {
        try {
            // 这里简化处理，实际应根据API支持的日期范围进行验证
            return date != null && !date.isEmpty();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取支持的城市列表
     */
    public String getSupportedCities() {
        // 这里应调用API获取支持的城市列表，简化处理
        return "北京,上海,广州,深圳,杭州,成都,重庆,武汉,西安,南京";
    }
}
